package com.wenwen.social.controller.advice;

import com.wenwen.social.controller.vo.ResultVO;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Collections;

@ControllerAdvice(annotations = RestController.class)
public class ResultHandlerAdvice implements ResponseBodyAdvice<Object> {

	@Override
	public boolean supports(MethodParameter returnType, Class converterType) {
		return true;
	}

	/**
	 * 统一返回格式
	 * @param body
	 * @param returnType
	 * @param mediaType
	 * @param converterType
	 * @param serverHttpRequest
	 * @param serverHttpResponse
	 * @return
	 */
	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType mediaType, Class converterType, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
		if (null == body) {
			return ResultVO.fail();
		}
		return ResultVO.success(body);
	}
}